<template>
	<div>
		<!-- 登录 -->
		<div style="min-height: 500px; width: 40%; border: 2px blue solid">
			<!-- <h3>登录</h3> -->
			<div style="margin-left: 2%; width: 90%">
				<h3 align="center">登录</h3>
				<table width="90%" border="1" cellspacing="0" style="line-height: 36px">
					<tbody>
						<tr>
							<td>手机号:</td>
							<td><input v-model="user.username" type="text" /></td>
						</tr>
						<tr>
							<td>密码:</td>
							<td><input v-model="user.password" type="text" /></td>
						</tr>
						<tr>
							<td></td>
							<td><input type="button" value="登录" @click="login()" /></td>
						</tr>
					</tbody>
				</table>
			</div>
		</div>
	</div>
</template>

<script>
export default {
	name: 'login',

	data() {
		return {
			user: {},
		};
	},

	methods: {
		login() {
			const that = this;
			let fd = new FormData();
			fd.append('username', that.user.username);
			fd.append('password', that.user.password);
			console.log('开始登录');
			// 提交FormData格式数据获取登录token
			this.$axios.post(`${this.$ip}/api/login`, fd, {
				headers: {
					'Content-Type': 'multipart/form-data'
				}
			}).then((resp) => {
				// 添加token到window
				window.localStorage.setItem('token', resp.data.data.token);
				that.$store.state.user.to = {headers: {'Authorization': `Bearer ${resp.data.data.token}`}}
				console.log(resp.data.data.token);


				that.$axios.get(`${that.$ip}/api/user/info`, {
					headers: {
						'Authorization': `Bearer ${resp.data.data.token}`
					}
				}).then((resp) => {
					console.log(resp.data);
					
					//将获取出来的信息存储到当前容器中
					that.$store.state.user.name = resp.data.data.uname;
					that.$store.state.user.pic = resp.data.data.pic;
					that.$store.state.user.role = resp.data.data.role;
					that.$store.state.user.token = window.localStorage.getItem("token");
					console.log(that.$store.state.user)

					if (resp.data.data.role == 'adm') {
						that.$store.state.user.roleName = "管理员"
						console.log("管理员系统")
						that.$router.push('/adm');
						return;
					}
					if (resp.data.data.role == 'tea') {
						that.$store.state.user.roleName = "教师"
						console.log("教师用户系统")
						that.$router.push('/tea');
						return;
					}
					if (resp.data.data.role == 'stu') {
						that.$store.state.user.roleName = "学生"
						console.log("学生用户系统")
						that.$router.push('/stu');
						return;
					}
				});
			});
		},
	},
};
</script>

<style></style>
